package sdfi.lee.DAO;

import java.sql.Connection;
import java.sql.ResultSet;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DAO {
	private static final String RESOURCE_PATH="/hibernate.cfg.xml";
	private static final ThreadLocal threadLocal=new ThreadLocal();
	private static final Configuration configuration=new Configuration();
	private static SessionFactory sessionFactory=null;
	public static Session openSession()
	{
		 Session session = (Session) threadLocal.get();

	        if (session == null) {
	            if (sessionFactory == null) {
	                try {
	                    configuration.configure(RESOURCE_PATH);
	                    sessionFactory = configuration.buildSessionFactory();
	                }
	                catch (Exception e) {
	                    System.err.println("%%%% Error Creating SessionFactory %%%%");
	                    e.printStackTrace();
	                }
	            }
	            session = sessionFactory.openSession();
	            threadLocal.set(session);
	        }

	        return session;
		
	}
	public static void closeSession()
	{
		Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
	}
	public static synchronized int getAccount(String sql)
	{
		try
		{
		Session session =openSession();
		Connection con=session.connection();
		con.setAutoCommit(false);
		ResultSet rs=con.createStatement().executeQuery(sql);
		con.commit();
		
		if(rs.next())
		return rs.getInt("c");
		else return 0;
		}
		catch(Exception  ee)
		{
			ee.printStackTrace();
			return 0;
		}
		finally
		{
			
			DAO.closeSession();
		}
	}
	public static synchronized String getValueByexecuteSQL(String sql,String indexlabel)
	{
		try
		{
		Session session =openSession();
		Connection con=session.connection();
		con.setAutoCommit(false);
		ResultSet rs=con.createStatement().executeQuery(sql);
		con.commit();
		
		if(rs.next())
		return rs.getString(indexlabel);
		else return "未知项";
		}
		catch(Exception  ee)
		{
			ee.printStackTrace();
			return "未知项";
		}
		finally
		{
			
			DAO.closeSession();
		}
		
	}
}
